package com.xhs.config;

import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

/**
 * @desc: MongoDB多数据源配置
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-11-23 023 16:06
 * @version: JDK 1.8
 */

@Configuration
public class MongoConfig {

    @Autowired
    private MongoClient mongoClient;

    @Autowired
    private MongoProperties mongoProperties;

    /**
     * 默认的数据库
     *
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient, mongoProperties.getDatabase());
    }

    /**
     * 第二个数据源
     *
     * @param adminUri uri
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplateLowCode(@Value("${spring.data.mongodb.low-code.uri}") String adminUri) {
        return new MongoTemplate(new SimpleMongoClientDatabaseFactory(adminUri));
    }

    /**
     * 第三个数据源
     *
     * @param adminUri uri
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplateEvent(@Value("${spring.data.mongodb.event.uri}") String adminUri) {
        return new MongoTemplate(new SimpleMongoClientDatabaseFactory(adminUri));
    }
}
